package com.igd.socket.sdk.nio.multi_reactor;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class Acceptor implements Runnable {
	int cores = Runtime.getRuntime().availableProcessors();
	private ServerSocketChannel serverSocketChannel;
	private Selector[] selectors = new Selector[cores];
	private SubSelector[] subSelectors = new SubSelector[cores];
	private Thread[] executeThread = new Thread[cores];
	private int index = 0;
	
	public Acceptor(ServerSocketChannel serverSocketChannel) {
		this.serverSocketChannel = serverSocketChannel;
		for(int i = 0; i < cores; i++) {
			try {
				selectors[i] = Selector.open();
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 该selector为子selector只用读写操作
			subSelectors[i] = new SubSelector(selectors[i]);
			executeThread[i] = new Thread(subSelectors[i]);
			executeThread[i].start();
		}
	}

	/**
	 * 该方法只做客户端连接操作
	 */
	@Override
	public void run() {
		try {
			SocketChannel socketChannel = serverSocketChannel.accept();
			System.out.println("multi-reactor-Server client-channal---isConnected：" + socketChannel.isConnected() + " isOpen：" + socketChannel.isOpen() + " isRegistered：" + socketChannel.isRegistered());
			socketChannel.configureBlocking(false);
			Selector selector = selectors[index];
			selector.wakeup();
			//注册读事件 将当前的客户端连接的socket注册进Work中
			SelectionKey readSelectionKey = socketChannel.register(selectors[index], SelectionKey.OP_READ);
			readSelectionKey.attach(new WorkHandler(socketChannel));
						
			if(++index == cores) {
				index = 0;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
